/*
 * ZBar4Android
 * 作者：秦元培
 * 时间：2013年12月21日
 * 需要解决的问题有：
 * 1、返回内容的正则解析
 * 2、如果锁屏后打开程序会报错
 * 3、没有校正框，画不出来啊，郁闷
 * 4、可能会与其它相机应用冲突，如微信
 * 5、条形码还是读不出来
 */
package com.socool.sinafaith.zbar;

import com.socool.sinafaith.zxing.camera.BeepManager;
import com.socool.sinofaith.R;
import com.socool.sinofaith.ui.AnswerQuestionActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Size;

import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;

public class ZBarMainActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;
    private BeepManager mBeepManager;


    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
    	try{
        System.loadLibrary("iconv");
    	}
    	catch(UnsatisfiedLinkError ex){
    		
    	}
    } 

    public void onCreate(Bundle savedInstanceState) {
    	try{
        super.onCreate(savedInstanceState);
        Window window = getWindow();
		 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_zbar);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        PackageManager pm=getPackageManager();
        Log.i("TAG", pm.checkPermission("android.permission.CAMERA", "com.socool.sinofaith")+  "   fale  ");

        	
        	autoFocusHandler = new Handler();
        	mCamera = getCameraInstance();

        	/* Instance barcode scanner */
        	scanner = new ImageScanner();
        	scanner.setConfig(0, Config.X_DENSITY, 3);
        	scanner.setConfig(0, Config.Y_DENSITY, 3);

        	mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

        	FrameLayout preview = (FrameLayout)findViewById(R.id.fl_zbar);
        	preview.addView(mPreview);
        	mBeepManager = new BeepManager(this);
        	mBeepManager.updatePrefs();
    	}catch(Exception ex){
    		Toast.makeText(ZBarMainActivity.this,
    				ex.getMessage(), Toast.LENGTH_LONG).show();
    		finish();
    	}

Log.i("TAG", "走到这里");
       
    }

    public void onPause() {
        super.onPause();
        releaseCamera();
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);
                
                if (result != 0) {
                	mBeepManager.playBeepSoundAndVibrate();
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();
                    String resultStr="";
                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {
                        resultStr=sym.getData();
                        barcodeScanned = true;
                    }

                    Intent intent=new Intent();
            		intent.putExtra("code", resultStr);
            		setResult(1, intent);
            		finish();
                    
                }
            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };
        
        protected void onStop() {
        	
        	super.onStop();
        	this.finish();
        };
}
